import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'dart:ui';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/BlankToolBarTool.dart';
import 'package:flutter_yres/tool/md5_sign.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class ForgetPage extends StatefulWidget {
  ForgetPage({Key key}) : super(key: key);

  @override
  _ForgetPageState createState() => _ForgetPageState();
}

class _ForgetPageState extends State<ForgetPage> {
  final _userNameController = TextEditingController(); //用户名
  final _userPwdController = TextEditingController(); //密码
  final _userPwdController2 = TextEditingController(); //密码
  final _userCodeController = TextEditingController(); //验证码
  final _userReferrerController = TextEditingController(); //邀请人
  // 响应空白处的焦点的Node
  BlankToolBarModel barModel = BlankToolBarModel();
  ScrollController scrollController = ScrollController();

  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;

  @override
  Widget build(BuildContext context) {
    double kWindowstateHeight = MediaQueryData.fromWindow(window).padding.top; //状态栏
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Scaffold(
        appBar: AppBar(
          title:Text('忘记密码'),
        ),
        body: 
        BlankToolBarTool.blankToolBarWidget(context,
            model: barModel,
            body: Container(
                margin: EdgeInsets.fromLTRB(0, kWindowstateHeight, 0, 0),
                height: ScreenUtil.getInstance().setHeight(1334)-kWindowstateHeight-56,
                child: SingleChildScrollView(
                    controller: scrollController,
                    child: Column(
                      children: <Widget>[
                         Container(
                            child:  Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  createInputText(_userNameController,
                                      hint: '请输入用户名',
                                      imgPath: 'images/icon_iphone.png',
                                      obscureText: false,
                                      type: TextInputType.phone),
                                  createBtnInputText(_userCodeController,
                                      hint: '请输入验证码',
                                      imgPath: 'images/icon_iphone.png',
                                      obscureText: false,
                                      type: TextInputType.phone),
                                  createInputText(_userPwdController,
                                      hint: '请输入密码',
                                      imgPath: 'images/icon_lock.png',
                                      obscureText: true,
                                      type: TextInputType.visiblePassword),
                                  createInputText(_userPwdController2,
                                      hint: '请再次输入密码',
                                      imgPath: 'images/icon_lock.png',
                                      obscureText: true,
                                      type: TextInputType.visiblePassword),
                                  new Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0.0,  ScreenUtil.getInstance().setWidth(20)  * 2, 0, 0.0),
                                      width: ScreenUtil.getInstance().setWidth(750) * 0.8,
                                      child: new RaisedButton(
                                          color: Colors.blue,
                                          shape: StadiumBorder(),
                                          child: new Padding(
                                            padding: new EdgeInsets.all(10.0),
                                            child: new Text(
                                              '找回密码',
                                              style: new TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 16.0),
                                            ),
                                          ),
                                          onPressed: () {
                                            requestForget();
                                          })),
                                  // new Container(
                                  //     margin: EdgeInsets.fromLTRB(
                                  //         0.0, kMargin20 * 2, 0, kMargin20 * 8),
                                  //     width: kScreenWidth * 0.8,
                                  //     child: new RaisedButton(
                                  //         color: Colors.blue,
                                  //         shape: StadiumBorder(),
                                  //         child: new Padding(
                                  //           padding: new EdgeInsets.all(10.0),
                                  //           child: new Text(
                                  //             '返回登录',
                                  //             style: new TextStyle(
                                  //                 color: Colors.white,
                                  //                 fontSize: 16.0),
                                  //           ),
                                  //         ),
                                  //         onPressed: () {
                                  //           Navigator.pop(context, '');
                                  //         })),
                                ])
                         ),
                      ],
                    )))
                    )
                    );
  }

//图标 + 输���框
  Widget createInputText(TextEditingController controller,
      {obscureText: false, String hint, String imgPath, TextInputType type}) {
    FocusNode focusNode = barModel.getFocusNodeByController(controller);
    return Padding(
        padding:
            new EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20) * 2, ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20) * 2, 0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Image.asset(
                      imgPath,
                      fit: BoxFit.fill,
                    ),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750)*0.6,
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText,
                        focusNode: focusNode),
                  ),
                  new IconButton(
                    icon: new Icon(Icons.clear, color: Colors.black45),
                    onPressed: () {
                      controller.clear();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

//图标 + 输入框+ 按钮
  Widget createBtnInputText(TextEditingController controller,
      {obscureText: false, String hint, String imgPath, TextInputType type}) {
    return Padding(
        padding:
            new EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20) * 2, ScreenUtil.getInstance().setWidth(20), ScreenUtil.getInstance().setWidth(20) * 2, 0),
        child: new Stack(
          alignment: new Alignment(1.0, 1.0),
          //statck
          children: <Widget>[
            new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0),
                    child: new Image.asset(
                      imgPath,
                      fit: BoxFit.fill,
                    ),
                  ),
                  new Container(
                    width: ScreenUtil.getInstance().setWidth(750)*0.5,
                    child: new TextField(
                        // focusNode: _contentFocusNode,
                        controller: controller,
                        keyboardType: type,
                        decoration: new InputDecoration(
                          border: InputBorder.none,
                          hintText: hint,
                        ),
                        obscureText: obscureText),
                  ),
                  new MaterialButton(
                    color: codeStatus == 1 ? Colors.blue : Colors.grey,
                    textColor: Colors.white,
                    child: new Text(codeString),
                    onPressed: () {
                      sendCode();
                    },
                  ),
                ]),
            Divider(
              height: 1,
            ),
          ],
        ));
  }

  void _scrollTo() {
    //滑动到指定位置
    scrollController.jumpTo(100);
  }

  @override
  void initState() {
    super.initState();
    barModel.outSideCallback = focusNodeChange;
  }

  void focusNodeChange() {
    print(barModel.focusNodeListener());
    barModel.focusNodeListener();
    setState(() {});
  }

  // 保存账号密码
  void _saveLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString("name", _userNameController.text);
    preferences.setString("pwd", _userPwdController.text);
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    barModel.removeFocusListeners();
    super.dispose();
  }

  sendCode() async {
    //发送短信验证码
    Map map = Map();
    map["phone"] = _userNameController.text;
    map['sign_type'] = 'yres.sms';
    // FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    // map['type'] = "mkyx.sms";
    // map = getSign(map);

    // FormData data = new FormData.fromMap({
    //   "phone": _userNameController.text,
    //   "timestamp": map['timestamp'],
    //   "data_type": map['data_type'],
    //   "version": map['version'],
    //   "sign": map['sign'],
    //   'type': map['type']
    // });
    Response<String> response =
        await HttpUtil().post(Api.SendUserFindpwdUrl, data: getSign(map));
    Map userMap = json.decode(response.data);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      print(userMap);
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
  }

  requestForget() async {
    if (_userNameController.text == '' ||
        _userPwdController.text == '' ||
        _userPwdController2.text == '' ||
        _userCodeController.text == '') {
      Toast.toast(context, msg: '填写完整注册信息');
      return;
    }
    if( _userPwdController2.text!= _userPwdController.text){
       Toast.toast(context, msg: '两次密码不一致');
      return;
    }
    // FocusScope.of(context).requestFocus();
    FormData formData= new FormData.fromMap({
        "phone": _userNameController.text,
        "code": _userCodeController.text,
        "pwd": _userPwdController.text
      });
    print(formData);
    Response<String> response =
        await HttpUtil().post(Api.FindPwdByPhoneUrl, data: formData);
    Map userMap = json.decode(response.data);
    print(userMap);
    Toast.toast(context, msg: userMap['msg']);
    int code = userMap['code'];
    if (code == 1) {
      _saveLoginMsg();
      // Navigator.pop(context, '');
    } else {}
  }
}
